/**
 * 
 */
package com.alstudio.ui.module.notice;

import java.util.ArrayList;

import android.content.Context;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;

import com.alstudio.app.ALLocalEnv;
import com.alstudio.core.message.ALMessageNotificationManager;
import com.alstudio.core.message.LoadMessageCallback;
import com.alstudio.core.message.system.SystemMessageManager;
import com.alstudio.module.xmpp.protocol.xmpp.packact.ALMessage;
import com.alstudio.ui.base.TitleBarActivity;
import com.alstudio.view.absadapter.BaseUserListAdapter.AddOnIconClickListener;
import com.alstudio.view.dialog.AlertDialogCreator;
import com.alstudio.view.listener.AlDialogOnClickListener;
import com.alstudio.view.listview.PullRefreshExpandableListView;
import com.alstudio.view.listview.PullRefreshExpandableListView.RankViewLoadStateListener;
import com.loovee.imaohu.R;
import com.nhaarman.listviewanimations.itemmanipulation.AnimateDismissAdapter;
import com.nhaarman.listviewanimations.itemmanipulation.ExpandCollapseListener;
import com.nhaarman.listviewanimations.itemmanipulation.OnDismissCallback;

/**
 * 系统消息界面
 * 
 * @author alonso lee
 * 
 */
public class SystemNoticeActivity extends TitleBarActivity implements
		RankViewLoadStateListener, OnItemClickListener, AddOnIconClickListener,
		ExpandCollapseListener {

	private SystemNoticeAdapter2 mSystemNoticeAdapter;

	// 显示用户数据的view
	private PullRefreshExpandableListView listview;

	private ArrayList<ALMessage> msgs;

	private boolean isEditing = false;

	// 保存前一次展开通知位置
	private int preClickGroupPosition = -1;
	private boolean isExpending = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setupView(getApplicationContext(), getClass().getSimpleName());
		initData();
	}

	@Override
	protected void setupView(Context context, String name) {
		// TODO Auto-generated method stub
		super.setupView(context, name);
		setTitleBarActivityContentView(R.layout.system_notice_layout);

		setCenterTextViewMessage(R.string.TxtSystemNotice);

		rightUseImageButton(true);
		setRightButtonImageSrc(R.drawable.personal_title_icon_set);

		listview = (PullRefreshExpandableListView) findViewById(R.id.listview);

		// 禁止下拉刷新
		listview.disablePullRefresh();
		// 不要声音
		listview.setSoundEffectsEnabled(false);

		msgs = new ArrayList<ALMessage>();
		mSystemNoticeAdapter = new SystemNoticeAdapter2(
				getApplicationContext(), ALLocalEnv.getLocalEnv()
						.getGlobalLayoutInflater(), msgs);
		mSystemNoticeAdapter.setAbsListView(listview.getListView());

		mSystemNoticeAdapter.setExpandCollapseListener(this);

		// mSystemNoticeAdapter.setAddOnIconClickListener(this);
		// mSystemNoticeAdapter
		// .setDeleteIconClickListener(deleteIconClickListener);
		listview.setLoadStateListener(this);
		listview.setItemClickListener(this);

		systemAnimateDismissAdapter = new AnimateDismissAdapter(
				mSystemNoticeAdapter, SystemOnDismissCallback);
		systemAnimateDismissAdapter.setAbsListView(listview.getListView());

		listview.setAdapter(mSystemNoticeAdapter);

		mSystemNoticeAdapter.setDeleteClickListener(deleteIconClickListener);

		initExpandListViewGroupListener();
	}

	private void initExpandListViewGroupListener() {/*
													 * listview.getListView().
													 * setOnGroupExpandListener(
													 * new
													 * OnGroupExpandListener() {
													 * 
													 * @Override public void
													 * onGroupExpand(int
													 * groupPosition) {
													 * 
													 * if (preClickGroupPosition
													 * != -1 &&
													 * preClickGroupPosition !=
													 * groupPosition) {
													 * listview.
													 * getListView().collapseGroup
													 * ( preClickGroupPosition);
													 * } preClickGroupPosition =
													 * groupPosition;
													 * isExpending = true;
													 * 
													 * }
													 * 
													 * });
													 * 
													 * listview.getListView().
													 * setOnGroupCollapseListener
													 * ( new
													 * OnGroupCollapseListener()
													 * {
													 * 
													 * @Override public void
													 * onGroupCollapse(int
													 * groupPosition) {
													 * 
													 * isExpending = false; }
													 * });
													 */
	}

	@Override
	protected void initData() {
		// TODO Auto-generated method stub
		loadSystemMessage();
		new Thread(){
			public void run() {
				ALMessageNotificationManager.getDefaultALMessageNotificationManager().cancelSystemNotification();
			};
		}.start();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.BaseActivity#onStart()
	 */
	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();
	}

	@Override
	public void onAddOnIconClick(Object obj) {
		// TODO Auto-generated method stub

	}

	/**
	 * 读取留言消息
	 */
	private void loadSystemMessage() {
		SystemMessageManager.getSystemMessageManager().loadSystemMessage(
				msgs.size(), loadSystemMessagesCallback);
	}

	private LoadMessageCallback loadSystemMessagesCallback = new LoadMessageCallback() {

		@Override
		public void onLoadCompleted(Object obj) {

			// TODO Auto-generated method stub
			@SuppressWarnings("unchecked")
			ArrayList<ALMessage> temp = (ArrayList<ALMessage>) obj;
			msgs.addAll(temp);
			if (temp.size() == 0
					|| temp.size() < ALLocalEnv.LOAD_MORE_COUNT_PER_TIME) {
				// 没有更多了
				listview.updateLoadMoreState(false);
			}
			listview.onLoadMoreCompleted();

			temp.clear();
			temp = null;

			if (msgs.size() == 0) {
				listview.showNoDataInfo(R.drawable.me_myphone_icon_empty01,
						getString(R.string.TxtNoCallHistoryHint));
			} else {
				listview.showRefereshListView();
				mSystemNoticeAdapter.notifyDataSetChanged();
			}

		}
	};

	private void addNewSystemMessage(ALMessage msg) {
		msgs.add(0, msg);
		listview.showRefereshListView();
		mSystemNoticeAdapter.notifyDataSetChanged();

	}

	@Override
	public void handleNewSystemMessageEvent(ALMessage msg) {
		// TODO Auto-generated method stub
		super.handleNewSystemMessageEvent(msg);
		addNewSystemMessage(msg);
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long id) {
		// TODO Auto-generated method stub

		// TODO Auto-generated method stub
		if (isEditing)
			return;
		if (id == -1) {
			// 点击的是headerView或者footerView
			return;
		}
		int realPosition = (int) id;
		ALMessage info = msgs.get(realPosition);
		if (info == null)
			return;

	}

	@Override
	public void onLoadMore(PullRefreshExpandableListView view) {
		// TODO Auto-generated method stub
		loadSystemMessage();
	}

	@Override
	public void onRefresh(PullRefreshExpandableListView view) {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {

		menu.clear();
		menu.add(Menu.FIRST, Menu.FIRST + 1, Menu.FIRST + 1,
				getString(R.string.TxtAllRead));
		menu.add(Menu.FIRST + 1, Menu.FIRST + 2, Menu.FIRST + 2,
				getString(R.string.TxtAllDelete));
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		boolean isDelete = false;
		if (item.getItemId() == Menu.FIRST + 1) {

		} else if (item.getItemId() == Menu.FIRST + 2) {
			isDelete = true;
		}
		showMenuOptDialog(isDelete);
		return super.onOptionsItemSelected(item);
	}

	private void showMenuOptDialog(final boolean isDelete) {
		// 全部已读
		String msg = getString(R.string.TxtAllReadInfo);
		if (isDelete) {
			msg = getString(R.string.TxtAllDeleteInfo);
		}

		AlertDialogCreator mDialogCreator = AlertDialogCreator
				.createTwoButtonNormalDialog(this, false);
		mDialogCreator.setLeftKeyListener(new AlDialogOnClickListener() {

			@Override
			public void onClick() {
				if (isDelete) {
					SystemMessageManager.getSystemMessageManager()
							.deleteAllMessage();
					msgs.clear();
					listview.showNoDataInfo(R.drawable.me_myphone_icon_empty01,
							getString(R.string.TxtNoCallHistoryHint));
				} else {
					SystemMessageManager.getSystemMessageManager()
							.setAllMessageReaded();
					for (ALMessage msg : msgs) {
						msg.setDisplayed(true);
					}
					mSystemNoticeAdapter.notifyDataSetChanged();

				}
			}
		});

		mDialogCreator.setMessage(msg);

		mDialogCreator.showDialog();
	}

	/**************************************** 删除 ***********************************************/
	private AnimateDismissAdapter systemAnimateDismissAdapter;;

	private AddOnIconClickListener deleteIconClickListener = new AddOnIconClickListener() {

		@Override
		public void onAddOnIconClick(Object obj) {
			// TODO Auto-generated method stub
			// 删除指定位置的记录
			int pos = (Integer) obj;
			systemAnimateDismissAdapter.animateDismiss(pos);
		}
	};

	private OnDismissCallback SystemOnDismissCallback = new OnDismissCallback() {

		@Override
		public void onDismiss(AbsListView arg0, int[] reverseSortedPositions) {
			// TODO Auto-generated method stub
			for (int position : reverseSortedPositions) {
				if (position < msgs.size()) {
					ALMessage msg = msgs.remove(position);
					mSystemNoticeAdapter.notifyDataSetChanged();
					// 从数据库中删除
					SystemMessageManager.getSystemMessageManager()
							.deleteMessageById(msg.getMsgId());

					if (msgs.size() < 10) {
						// 重新读取数据库中的剩余数据
						loadSystemMessage();
					}

				}
			}
		}
	};

	/**************************************** 删除 ***********************************************/

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.alstudio.ui.base.TitleBarActivity#invokeRightBtnClick()
	 */
	@Override
	protected void invokeRightBtnClick() {
		// TODO Auto-generated method stub
		super.invokeRightBtnClick();

		isEditing = !isEditing;

		// adapter.setShowDelete(isEditing);
		// adapter.notifyDataSetChanged();

		if (!isEditing) {
			setRightButtonImageSrc(R.drawable.personal_title_icon_set);
		} else {
			setRightButtonImageSrc(R.drawable.friend_title_icon_confirm);
			if (preClickGroupPosition != -1) {
				if (mSystemNoticeAdapter.isExpanded(preClickGroupPosition)) {
					mSystemNoticeAdapter.collapse(preClickGroupPosition);
				}
			}
		}
		mSystemNoticeAdapter.setShowDelete(isEditing);
		mSystemNoticeAdapter.notifyDataSetChanged();

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.nhaarman.listviewanimations.itemmanipulation.ExpandCollapseListener
	 * #onItemCollapsed(int)
	 */
	@Override
	public void onItemCollapsed(int position) {
		// TODO Auto-generated method stub
		// mSystemNoticeAdapter.toggle(position);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.nhaarman.listviewanimations.itemmanipulation.ExpandCollapseListener
	 * #onItemExpanded(int)
	 */
	@Override
	public void onItemExpanded(int position) {
		// TODO Auto-generated method stub
		if (preClickGroupPosition != -1 && preClickGroupPosition != position) {
			if (mSystemNoticeAdapter.isExpanded(preClickGroupPosition)) {
				mSystemNoticeAdapter.collapse(preClickGroupPosition);
			}
		}
		preClickGroupPosition = position;
	}

}
